<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生管理系统</title>
    <link rel="stylesheet" href="css/bootstrap-icons.css">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
        }
        .sidebar {
            background-color: #343a40;
            color: white;
            height: 100vh;
            position: fixed;
            padding-top: 20px;
        }
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            margin-bottom: 5px;
        }
        .sidebar .nav-link:hover, .sidebar .nav-link.active {
            color: white;
            background-color: rgba(255, 255, 255, 0.1);
        }
        .sidebar .nav-link i {
            margin-right: 10px;
        }
        .main-content {
            margin-left: 250px;
            padding: 20px;
        }
        .card {
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .table th {
            background-color: #f8f9fa;
        }
        .modal-header {
            background-color: #343a40;
            color: white;
        }
        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
        }
        .pagination {
            justify-content: center;
        }
        .search-box {
            max-width: 300px;
        }
        
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 sidebar">
                <h4 class="text-center mb-4">学生管理系统</h4>
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link active" href="#" id="class-tab">
                            <i class="bi bi-people-fill"></i> 班级管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#" id="student-tab">
                            <i class="bi bi-person-fill"></i> 学生管理
                        </a>
                    </li>
                </ul>
            </div>

            <!-- 主内容区 -->
            <div class="col-md-10 main-content">
                <!-- 班级管理 -->
                <div id="class-management">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h3>班级管理</h3>
                        <button class="btn btn-primary" id="add-class-btn">
                            <i class="bi bi-plus-lg"></i> 添加班级
                        </button>
                    </div>
                    
                    <div class="card">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover" id="class-table">
                                    <thead>
                                        <tr>
                                            <th>班级ID</th>
                                            <th>班级名称</th>
                                            <th>班主任</th>
                                            <th>班级人数</th>
                                            <th>创建时间</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- 班级数据将通过JS动态加载 -->
                                    </tbody>
                                </table>
                            </div>
                            <nav aria-label="Page navigation">
                                <ul class="pagination" id="class-pagination">
                                    <!-- 分页将通过JS动态加载 -->
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>

                <!-- 学生管理 -->
                <div id="student-management" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h3>学生管理</h3>
                        <div>
                            <select class="form-select me-2 d-inline-block w-auto" id="class-filter">
                                <option value="">所有班级</option>
                                <!-- 班级选项将通过JS动态加载 -->
                            </select>
                            <button class="btn btn-primary" id="add-student-btn">
                                <i class="bi bi-plus-lg"></i> 添加学生
                            </button>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-body">
                            <div class="mb-3">
                                <div class="input-group search-box">
                                    <input type="text" class="form-control" placeholder="搜索学生姓名..." id="student-search">
                                    <button class="btn btn-outline-secondary" type="button" id="search-student-btn">
                                        <i class="bi bi-search"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-hover" id="student-table">
                                    <thead>
                                        <tr>
                                            <th>学生ID</th>
                                            <th>头像</th>
                                            <th>姓名</th>
                                            <th>性别</th>
                                            <th>年龄</th>
                                            <th>班级</th>
                                            <th>联系电话</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- 学生数据将通过JS动态加载 -->
                                    </tbody>
                                </table>
                            </div>
                            <nav aria-label="Page navigation">
                                <ul class="pagination" id="student-pagination">
                                    <!-- 分页将通过JS动态加载 -->
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑班级模态框 -->
    <div class="modal fade" id="class-modal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="class-modal-title">添加班级</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="class-form">
                        <input type="hidden" id="class-id">
                        <div class="mb-3">
                            <label for="class-name" class="form-label">班级名称</label>
                            <input type="text" class="form-control" id="class-name" required>
                        </div>
                        <div class="mb-3">
                            <label for="class-teacher" class="form-label">班主任</label>
                            <input type="text" class="form-control" id="class-teacher">
                        </div>
                        <div class="mb-3">
                            <label for="class-size" class="form-label">班级人数</label>
                            <input type="number" class="form-control" id="class-size" min="0">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="save-class-btn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑学生模态框 -->
    <div class="modal fade" id="student-modal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="student-modal-title">添加学生</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="student-form">
                        <input type="hidden" id="student-id">
                        <div class="mb-3">
                            <label for="student-name" class="form-label">姓名</label>
                            <input type="text" class="form-control" id="student-name" required>
                        </div>
                        <div class="mb-3">
                            <label for="gender" class="form-label">性别</label>
                            <select class="form-select" id="gender">
                                <option value="男">男</option>
                                <option value="女">女</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="age" class="form-label">年龄</label>
                            <input type="number" class="form-control" id="age" min="0" max="100">
                        </div>
                        <div class="mb-3">
                            <label for="phone" class="form-label">联系电话</label>
                            <input type="tel" class="form-control" id="phone">
                        </div>
                        <div class="mb-3">
                            <label for="email" class="form-label">电子邮箱</label>
                            <input type="email" class="form-control" id="email">
                        </div>
                        <div class="mb-3">
                            <label for="address" class="form-label">家庭住址</label>
                            <input type="text" class="form-control" id="address">
                        </div>
                        <div class="mb-3">
                            <label for="student-class" class="form-label">所属班级</label>
                            <select class="form-select" id="student-class">
                                <!-- 班级选项将通过JS动态加载 -->
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="avatar" class="form-label">头像URL</label>
                            <input type="text" class="form-control" id="avatar" placeholder="输入图片链接">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="save-student-btn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal fade" id="confirm-modal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">确认删除</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p id="confirm-message">您确定要删除此项吗？</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirm-delete-btn">删除</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 引入必要的JS库 -->
    <script src="js/jquery.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            // 全局变量
            let currentTab = 'class';
            let currentClassPage = 1;
            let currentStudentPage = 1;
            let totalClassPages = 1;
            let totalStudentPages = 1;
            let classFilter = '';
            let studentSearch = '';
            let classes = [];
            let students = [];
            let deleteType = '';
            let deleteId = 0;

            // 初始化模态框
            const classModal = new bootstrap.Modal(document.getElementById('class-modal'));
            const studentModal = new bootstrap.Modal(document.getElementById('student-modal'));
            const confirmModal = new bootstrap.Modal(document.getElementById('confirm-modal'));

            // 切换标签页
            $('#class-tab').click(function() {
                currentTab = 'class';
                $('#class-management').show();
                $('#student-management').hide();
                $('#class-tab').addClass('active');
                $('#student-tab').removeClass('active');
                loadClasses();
            });

            $('#student-tab').click(function() {
                currentTab = 'student';
                $('#class-management').hide();
                $('#student-management').show();
                $('#student-tab').addClass('active');
                $('#class-tab').removeClass('active');
                loadStudents();
            });

            // 加载班级数据
            function loadClasses() {
                $.ajax({
                    url: 'http://localhost:8080/api/classes',
                    type: 'GET',
                    data: {
                        page: currentClassPage
                    },
                    success: function(response) {
                        classes = response.data || response;
                        renderClassTable();
                        renderClassPagination();
                    },
                    error: function(xhr) {
                        alert('加载班级数据失败: ' + xhr.responseText);
                    }
                });
            }

            // 渲染班级表格
            function renderClassTable() {
                const $tbody = $('#class-table tbody');
                $tbody.empty();

                if (classes.length === 0) {
                    $tbody.append('<tr><td colspan="6" class="text-center">暂无数据</td></tr>');
                    return;
                }

                classes.forEach(clazz => {
                    $tbody.append(`
                        <tr>
                            <td>${clazz.class_id}</td>
                            <td>${clazz.class_name}</td>
                            <td>${clazz.class_teacher || '-'}</td>
                            <td>${clazz.class_size || 0}</td>
                            <td>${new Date(clazz.create_time).toLocaleString()}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary edit-class-btn" data-id="${clazz.class_id}">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-danger delete-class-btn" data-id="${clazz.class_id}">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </td>
                        </tr>
                    `);
                });

                // 绑定编辑和删除按钮事件
                $('.edit-class-btn').click(function() {
                    const id = $(this).data('id');
                    editClass(id);
                });

                $('.delete-class-btn').click(function() {
                    const id = $(this).data('id');
                    showConfirmModal('class', id, '确定要删除这个班级吗？');
                });
            }

            // 渲染班级分页
            function renderClassPagination() {
                const $pagination = $('#class-pagination');
                $pagination.empty();

                if (totalClassPages <= 1) return;

                // 上一页按钮
                $pagination.append(`
                    <li class="page-item ${currentClassPage === 1 ? 'disabled' : ''}">
                        <a class="page-link" href="#" aria-label="Previous" id="class-prev">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                `);

                // 页码按钮
                for (let i = 1; i <= totalClassPages; i++) {
                    $pagination.append(`
                        <li class="page-item ${i === currentClassPage ? 'active' : ''}">
                            <a class="page-link" href="#" data-page="${i}">${i}</a>
                        </li>
                    `);
                }

                // 下一页按钮
                $pagination.append(`
                    <li class="page-item ${currentClassPage === totalClassPages ? 'disabled' : ''}">
                        <a class="page-link" href="#" aria-label="Next" id="class-next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                `);

                // 绑定分页按钮事件
                $('.page-link[data-page]').click(function(e) {
                    e.preventDefault();
                    currentClassPage = parseInt($(this).data('page'));
                    loadClasses();
                });

                $('#class-prev').click(function(e) {
                    e.preventDefault();
                    if (currentClassPage > 1) {
                        currentClassPage--;
                        loadClasses();
                    }
                });

                $('#class-next').click(function(e) {
                    e.preventDefault();
                    if (currentClassPage < totalClassPages) {
                        currentClassPage++;
                        loadClasses();
                    }
                });
            }

            // 加载学生数据
            function loadStudents() {
    console.log("查询生死12")
    $.ajax({
        url: 'http://localhost:8080/api/students/search', // 修改为/search端点
        type: 'GET',
        data: {
            name: studentSearch,
            classId: classFilter
        },
        success: function(response) {
            console.log(response)
            students = response;
            renderStudentTable();
            renderStudentPagination();
        },
        error: function(xhr) {
            alert('加载学生数据失败: ' + xhr.responseText);
        }
    });
}

            // 渲染学生表格
            function renderStudentTable() {
                const $tbody = $('#student-table tbody');
                $tbody.empty();

                if (students.length === 0) {
                    $tbody.append('<tr><td colspan="8" class="text-center">暂无数据</td></tr>');
                    return;
                }

                students.forEach(student => {
                    const classInfo = classes.find(c => c.class_id === student.class_id);
                    const className = classInfo ? classInfo.class_name : '未分配班级';
                    
                    $tbody.append(`
                        <tr>
                            <td>${student.student_id}</td>
                            <td>
                                <img src="images/default-avatar.png" alt="头像" class="avatar">
                            </td>
                            <td>${student.student_name}</td>
                            <td>${student.gender || '-'}</td>
                            <td>${student.age || '-'}</td>
                            <td>${className}</td>
                            <td>${student.phone || '-'}</td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary edit-student-btn" data-id="${student.student_id}">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-sm btn-outline-danger delete-student-btn" data-id="${student.student_id}">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </td>
                        </tr>
                    `);
                });

                // 绑定编辑和删除按钮事件
                $('.edit-student-btn').click(function() {
                    const id = $(this).data('id');
                    editStudent(id);
                });

                $('.delete-student-btn').click(function() {
                    const id = $(this).data('id');
                    showConfirmModal('student', id, '确定要删除这个学生吗？');
                });
            }

            // 渲染学生分页
            function renderStudentPagination() {
                const $pagination = $('#student-pagination');
                $pagination.empty();

                if (totalStudentPages <= 1) return;

                // 上一页按钮
                $pagination.append(`
                    <li class="page-item ${currentStudentPage === 1 ? 'disabled' : ''}">
                        <a class="page-link" href="#" aria-label="Previous" id="student-prev">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                `);

                // 页码按钮
                for (let i = 1; i <= totalStudentPages; i++) {
                    $pagination.append(`
                        <li class="page-item ${i === currentStudentPage ? 'active' : ''}">
                            <a class="page-link" href="#" data-page="${i}">${i}</a>
                        </li>
                    `);
                }

                // 下一页按钮
                $pagination.append(`
                    <li class="page-item ${currentStudentPage === totalStudentPages ? 'disabled' : ''}">
                        <a class="page-link" href="#" aria-label="Next" id="student-next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                `);

                // 绑定分页按钮事件
                $('.page-link[data-page]').click(function(e) {
                    e.preventDefault();
                    currentStudentPage = parseInt($(this).data('page'));
                    loadStudents();
                });

                $('#student-prev').click(function(e) {
                    e.preventDefault();
                    if (currentStudentPage > 1) {
                        currentStudentPage--;
                        loadStudents();
                    }
                });

                $('#student-next').click(function(e) {
                    e.preventDefault();
                    if (currentStudentPage < totalStudentPages) {
                        currentStudentPage++;
                        loadStudents();
                    }
                });
            }

            // 加载班级选项
            function loadClassOptions() {
                $.ajax({
                    url: 'http://localhost:8080/api/classes',
                    type: 'GET',
                    success: function(response) {
                        const classList = response.data || response;
                        const $classFilter = $('#class-filter');
                        const $studentClass = $('#student-class');
                        
                        // 清空现有选项
                        $classFilter.empty();
                        $studentClass.empty();
                        
                        // 添加默认选项
                        $classFilter.append('<option value="">所有班级</option>');
                        $studentClass.append('<option value="">未分配班级</option>');
                        
                        // 添加班级选项
                        classList.forEach(clazz => {
                            $classFilter.append(`<option value="${clazz.class_id}">${clazz.class_name}</option>`);
                            $studentClass.append(`<option value="${clazz.class_id}">${clazz.class_name}</option>`);
                        });
                        
                        classes = classList;
                    },
                    error: function(xhr) {
                        alert('加载班级选项失败: ' + xhr.responseText);
                    }
                });
            }

            // 添加班级
            $('#add-class-btn').click(function() {
                $('#class-modal-title').text('添加班级');
                $('#class-id').val('');
                $('#class-name').val('');
                $('#class-teacher').val('');
                $('#class-size').val('');
                classModal.show();
            });

            // 编辑班级
            function editClass(id) {
                const clazz = classes.find(c => c.class_id === id);
                if (!clazz) return;

                $('#class-modal-title').text('编辑班级');
                $('#class-id').val(clazz.class_id);
                $('#class-name').val(clazz.class_name);
                $('#class-teacher').val(clazz.class_teacher || '');
                $('#class-size').val(clazz.class_size || '');
                classModal.show();
            }

            // 保存班级
            $('#save-class-btn').click(function() {
                const id = $('#class-id').val();
                const data = {
                    class_name: $('#class-name').val(),
                    class_teacher: $('#class-teacher').val(),
                    class_size: $('#class-size').val() || 0
                };

                if (!data.class_name) {
                    alert('班级名称不能为空');
                    return;
                }

                const url = id ? `http://localhost:8080/api/classes/${id}` : 'http://localhost:8080/api/classes';
                const method = id ? 'PUT' : 'POST';

                $.ajax({
                    url: url,
                    type: method,
                    contentType: 'application/json',
                    data: JSON.stringify(data),
                    success: function() {
                        alert('保存成功');
                        classModal.hide();
                        loadClasses();
                        loadClassOptions(); // 刷新班级选项
                    },
                    error: function(xhr) {
                        alert('保存失败: ' + xhr.responseText);
                    }
                });
            });

            // 添加学生
            $('#add-student-btn').click(function() {
                $('#student-modal-title').text('添加学生');
                $('#student-id').val('');
                $('#student-name').val('');
                $('#gender').val('男');
                $('#age').val('');
                $('#phone').val('');
                $('#email').val('');
                $('#address').val('');
                $('#student-class').val('');
                $('#avatar').val('');
                studentModal.show();
            });

            // 编辑学生
            function editStudent(id) {
                const student = students.find(s => s.student_id === id);
                if (!student) return;

                $('#student-modal-title').text('编辑学生');
                $('#student-id').val(student.student_id);
                $('#student-name').val(student.student_name);
                $('#gender').val(student.gender || '男');
                $('#age').val(student.age || '');
                $('#phone').val(student.phone || '');
                $('#email').val(student.email || '');
                $('#address').val(student.address || '');
                $('#student-class').val(student.class_id || '');
                $('#avatar').val(student.avatar || '');
                studentModal.show();
            }

            // 保存学生
            $('#save-student-btn').click(function() {
                const id = $('#student-id').val();
                const data = {
                    student_name: $('#student-name').val(),
                    gender: $('#gender').val(),
                    age: $('#age').val() || null,
                    phone: $('#phone').val() || null,
                    email: $('#email').val() || null,
                    address: $('#address').val() || null,
                    class_id: $('#student-class').val() || null,
                    avatar: $('#avatar').val() || null
                };

                if (!data.student_name) {
                    alert('学生姓名不能为空');
                    return;
                }

                const url = id ? `http://localhost:8080/api/students/${id}` : 'http://localhost:8080/api/students';
                const method = id ? 'PUT' : 'POST';

                $.ajax({
                    url: url,
                    type: method,
                    contentType: 'application/json',
                    data: JSON.stringify(data),
                    success: function() {
                        alert('保存成功');
                        studentModal.hide();
                        loadStudents();
                    },
                    error: function(xhr) {
                        alert('保存失败: ' + xhr.responseText);
                    }
                });
            });

            // 显示确认删除模态框
            function showConfirmModal(type, id, message) {
                deleteType = type;
                deleteId = id;
                $('#confirm-message').text(message);
                confirmModal.show();
            }

            // 确认删除
            $('#confirm-delete-btn').click(function() {
                let url = '';
                if (deleteType === 'class') {
                    url = `http://localhost:8080/api/classes/${deleteId}`;
                } else if (deleteType === 'student') {
                    url = `http://localhost:8080/api/students/${deleteId}`;
                }

                $.ajax({
                    url: url,
                    type: 'DELETE',
                    success: function() {
                        alert('删除成功');
                        confirmModal.hide();
                        if (deleteType === 'class') {
                            loadClasses();
                            loadClassOptions(); // 刷新班级选项
                        } else {
                            loadStudents();
                        }
                    },
                    error: function(xhr) {
                        alert('删除失败: ' + xhr.responseText);
                        confirmModal.hide();
                    }
                });
            });

            // 班级筛选
            $('#class-filter').change(function() {
                classFilter = $(this).val();
                currentStudentPage = 1;
                loadStudents();
            });

            // 学生搜索
            $('#search-student-btn').click(function() {
                console.log("搜索学生")
                studentSearch = $('#student-search').val();
                currentStudentPage = 1;
                console.log("搜索学生"+studentSearch)
                loadStudents();
                console.log("搜索学生"+111)
            });

            // 回车键触发搜索
            $('#student-search').keypress(function(e) {
                if (e.which === 13) {
                    studentSearch = $(this).val();
                    currentStudentPage = 1;
                    loadStudents();
                }
            });

            // 初始化
            loadClassOptions();
            loadClasses();
        });
    </script>
</body>
</html>